package com.xw.lianshou.service;

import com.xw.lianshou.dao.IndexDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

/**
 * @author xw
 * @date 2021/5/27 21:28
 */
@Service
public class IndexService {
    @Autowired
    private IndexDao indexDao;

    /**
     * 测试事物失效
     * try catch导致异常未被抛出，导致事物失效
     * 若不想让事物失效 建议在添加事物的方法中不要捕获异常
     * * @return
     */
    @Transactional
    public String insert(){
        try {
            String name = "xw";
            int j = indexDao.insert(name);
            int i = j / 0;
            return "success";
        }catch (Exception e){
            e.printStackTrace();
            //在catch中加入下面这句代码 事物依然生效
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return "fail";
        }
    }
}
